package com.atguigu.dga.meta.controller;

import com.alibaba.fastjson.JSON;
import com.atguigu.dga.meta.bean.TableMetaInfo;
import com.atguigu.dga.meta.bean.TableMetaInfoExtra;
import com.atguigu.dga.meta.bean.TableMetaInfoQuery;
import com.atguigu.dga.meta.bean.TableMetaInfoVO;
import com.atguigu.dga.meta.service.TableMetaInfoExtraService;
import com.atguigu.dga.meta.service.TableMetaInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 元数据表 前端控制器
 * </p>
 *
 * @author zhangchen
 * @since 2023-06-27
 */
@RestController
@RequestMapping("/tableMetaInfo")
public class TableMetaInfoController {

    @Autowired
    TableMetaInfoService tableMetaInfoService;

    @Autowired
    TableMetaInfoExtraService tableMetaInfoExtraService;

    @PostMapping("/init-tables/{schemaName}/{assessDate}")
    public   String initTableMeta(@PathVariable("schemaName")String schemanName ,
                                  @PathVariable("assessDate") String assessDate ) throws Exception {

        tableMetaInfoService.initTableMetaInfo(assessDate,schemanName);
        return "success";

    }

    @GetMapping("/table-list")
    public String  getTableList( TableMetaInfoQuery tableMetaInfoQuery){
        System.out.println("tableMetaInfoQuery = " + tableMetaInfoQuery);

        List<TableMetaInfoVO> tableMetaList = tableMetaInfoService.getTableMetaList(tableMetaInfoQuery);
        Integer tableMetaTotal = tableMetaInfoService.getTableMetaTotal(tableMetaInfoQuery);
        Map rsMap=new HashMap();
        rsMap.put("total",tableMetaTotal);
        rsMap.put("list",tableMetaList);

        String jsonString = JSON.toJSONString(rsMap);

        return jsonString;

    }

    @GetMapping("/table/{id}")
    public TableMetaInfo getTableMeta(@PathVariable("id") String id){

        TableMetaInfo tableMetaInfo = tableMetaInfoService.getById(id);

        TableMetaInfoExtra tableMetaInfoExtra = tableMetaInfoExtraService.getOne(new QueryWrapper<TableMetaInfoExtra>().eq("table_name", tableMetaInfo.getTableName()).eq("schema_name", tableMetaInfo.getSchemaName()));

        tableMetaInfo.setTableMetaInfoExtra(tableMetaInfoExtra);

        return tableMetaInfo;


    }

    @PostMapping("/tableExtra")
    public  String  saveTableExtra(@RequestBody TableMetaInfoExtra tableMetaInfoExtra){
        tableMetaInfoExtra.setUpdateTime(new Date());
        tableMetaInfoExtraService.saveOrUpdate(tableMetaInfoExtra);
        return "success";

    }


}
